import { useEffect, useRef } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { t } from 'src/locales';
import { PAGE_NOT_FOUND, PAGE_NOT_PERMISSION, PAGE_DEFAULT, PAGE_HOME } from 'src/constants';
import { useLocation, useNavigate, matchRoutes } from 'react-router-dom';
import { getToken, setToken } from 'src/utils/storage';
import { AppDispatch, RootState } from 'src/store';
import { getUserInfo, setUserToken } from 'src/store/action';
import { routeConfig } from 'src/router';
import { App } from 'antd';
interface IProps {
  children: React.ReactNode;
}

export default function RouterGuard(props: IProps) {
  const dispatch = useDispatch<AppDispatch>();
  const location = useLocation();
  const navigate = useNavigate();
  const storeToken = useSelector((state: RootState) => state.user.token);
  const { user: userInfo, loading } = useSelector((state: RootState) => state.user);
  const {
    menus: permissionMenus,
    dynamicRoute,
    defaultOpenPath: defaultRoutePath,
  } = useSelector((state: RootState) => state.permission);
  const pathname = useRef<string>();
  const token = getToken();
  const { message } = App.useApp();
  // 请求用户信息
  const requestUserInfo = () => {
    // 获取数据是异步操作，需要标识位 防止重复调用
    if (!userInfo.userId && !loading) {
      dispatch(getUserInfo());
    }
  };
  // 登录认证
  const outerAuthHandle = () => {
    pathname.current = location.pathname;
    if (location.pathname === '/login' && (token || storeToken)) {
      navigate('/');
      return false;
    }
    if ((token || storeToken) && !userInfo.userId) {
      token && !storeToken && dispatch(setUserToken(token));
      !token && storeToken && setToken(storeToken);
      requestUserInfo();
      return true;
    } else if (!token && !storeToken && location.pathname !== '/login') {
      message.error(t('login.expire'));
      navigate(`/login?redirect=${pathname.current}`);
      return false;
    }
    return true;
  };

  // 路由认证
  const authentication = () => {
    if (dynamicRoute === null) return;
    if ([PAGE_DEFAULT, PAGE_HOME].includes(location.pathname)) {
      return navigate(defaultRoutePath);
    }
    const baseRoute = [...dynamicRoute, ...routeConfig];
    const mathchs = matchRoutes(baseRoute, location.pathname) ?? [];
    const searchRoute = mathchs.find((item) => item?.pathnameBase === location.pathname);
    // 如果没有匹配到路由 则跳转到404
    if (!mathchs || mathchs.length === 0 || !searchRoute) {
      message.error(t('error.not_found'));
      navigate(PAGE_NOT_FOUND);
      return;
    }
    // 没在权限列表，并且是需要进行认证（notAuth = false）
    if (
      !permissionMenus.includes(searchRoute!.pathnameBase) &&
      !searchRoute?.route?.data?.notAuth
    ) {
      message.error(t('error.no_permission'));
      navigate(PAGE_NOT_PERMISSION);
      return;
    }
  };

  useEffect(() => {
    outerAuthHandle() && authentication();
  }, [location.pathname, dynamicRoute]);

  return props.children;
}
